package cn.gqr.service.impl;

import cn.gqr.entity.*;
import cn.gqr.mapper.OrderMapper;
import cn.gqr.service.OrderService;
import cn.gqr.tool.Toolkit;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author gqr
 * @company null
 * @create 2022-06-12 17:07
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private OrderMapper orderMapper;


    //根据订单id添加快递单号
    public boolean insertCourierNumberByOrderId(String courierNumber , Integer orderId) {
        int i = orderMapper.insertCourierNumberByOrderId(courierNumber, orderId);
        return i>0;
    }

    //取所有买家的订单信息和用户信息并且分页,可动态条件查询
    public Map selectOrderHeaderAndUser(UserOrderVO userOrderVO, int start, int num) {
        Map map = new HashMap();
        List<UserOrder> orders = orderMapper.selectOrderHeaderAndUser(userOrderVO , start, num);
        //所有买家的订单信息的总行数
        int total = orderMapper.selectOrderHeaderAndUserTotal(userOrderVO);
        map.put("orders",orders);
        map.put("total",total);
        return map;
    }


    //根据订单id,查找订单明细的所有对应书本信息
    public List<BookOrderDetail> selectBookOrderDetailsByOrderId(int orderId) {
        return orderMapper.selectBookOrderDetailsByOrderId(orderId);
    }


    //获取当前登录用户的所有订单信息并且分页以及条件查询
    public List<OrderInfo> selectUserOrderAllPage(Integer isPayment,String startingTime,String endTime, int start,int num) {
        List<OrderInfo> orderInfos = orderMapper.selectUserOrderAllPage(Toolkit.getUser().getId(),isPayment, startingTime, endTime, start, num);
        return orderInfos;
    }

    //更新收货地址及收货电话
    public boolean updateAddressAndPhoneByOrderId(Order order) {
        int i = orderMapper.updateAddressAndPhoneByOrderId(order);
        return i>0;
    }

    //更新订单付款状态  1已付款，0未付款
    public boolean updatePaymentStatusByOrderId(Order order) {
        order.setPaymentTime(new Date());
        order.setIsPayment(1);
        int i = orderMapper.updatePaymentStatusByOrderId(order);
        return i>0;
    }


    //添加订单明细添加订单
    @Transactional
    public Integer insert(CartOrder cartOrder) {

        Order order = cartOrder.getOrder();

        order.setUserId(Toolkit.getUser().getId());

        orderMapper.insert(order);

        List<OrderDetail> orderDetails = cartOrder.getOrderDetails();

        for(OrderDetail o:orderDetails){
            o.setOrderId(order.getId());
        }

        int i = orderMapper.addOrderDetailsList(orderDetails);

        if(i<orderDetails.size()){
            try {
                int x = 0/1;
            }catch (Exception e){
            }
        }
        return order.getId();
    }

}

